package com.sunshine.security;


import com.sunshine.bean.User;
import com.sunshine.exception.UnknownUserRoleException;
import com.sunshine.model.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by along on 4/20/18.
 */
@Service
@Primary
public class JwtUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        User user = loadNativUserByName(name);

        if (user == null) {
            throw new UsernameNotFoundException("user not found id :" + name);
        }

        try {
            return JwtUser.of(user);
        } catch (UnknownUserRoleException e) {
            throw new UsernameNotFoundException("system error [invalid role] :" + user.getRole());
        }
    }

    public User loadNativUserByName(String name) {
        return userMapper.findByName(name);
    }

    public List<User> loadAllNativeUser() {
        return userMapper.findAll();
    }
}
